package com.tanklab.signature.controller;

import com.tanklab.signature.common.util.JwtUtils;
import com.tanklab.signature.common.util.ResultCode;
import com.tanklab.signature.ds.req.UploadFileReq;
import com.tanklab.signature.ds.resp.CommonResp;
import com.tanklab.signature.service.FileUploadService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/signature/file")
@Api(tags = "文件上传接口")
public class FileUploadController {

    @Autowired
    private FileUploadService fileUploadService;

    @Autowired
    private JwtUtils jwtUtils;

    @ApiOperation(value = "上传文件并自动创建申请")
    @PostMapping("/upload")
    public CommonResp uploadFile(
            @ApiParam(value = "文件", required = true)
            @RequestParam("file") MultipartFile file,

            @ApiParam(value = "文件类型", required = true)
            @RequestParam("fileType") String fileType,

            @ApiParam(value = "文件描述")
            @RequestParam(value = "fileDescription", required = false) String fileDescription,

            @ApiParam(value = "文件名", required = true)
            @RequestParam("fileName") String fileName,

            HttpServletRequest request) {

        String token = request.getHeader("Authorization");
        if (token.startsWith("Bearer ")) {
            token = token.substring(7);
        }

        // 从Token提取openid
        String openid = jwtUtils.getOpenidFromToken(token);

        // 验证文件是否为空
        if (file.isEmpty()) {
            CommonResp resp = new CommonResp();
            resp.setRet(ResultCode.PARAM_ERROR);
            resp.setMsg("文件不能为空");
            return resp;
        }

        // 构造上传信息对象
        UploadFileReq uploadFileReq = new UploadFileReq();
        uploadFileReq.setFileType(fileType);
        uploadFileReq.setFileDescription(fileDescription);

        // 调用服务进行文件上传并自动创建申请
        return fileUploadService.uploadFile(file, fileName, uploadFileReq, openid);
    }
}